<template>
  <el-dialog
    :title="getTitle"
    :visible.sync="innerVisible"
    width="50%"
  >
    <el-form v-loading="httpLoading" class="el-form-col" :model="model" label-width="110px" label-position="left"
             ref="elForm">
      <el-row>

        <template v-if="showHeader">
          <el-col :span="24">
            <el-form-item label="服务类型:">
              <span v-if="serviceTypeList.length > 0" :key="item"
                    v-for="item in serviceTypeList">{{ item | filterDataBaseDictionary }}&nbsp;&nbsp; </span>
              <span v-if="serviceTypeList.length == 0">无</span>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <template v-if="hasOrderSourceCodeScm">
              <el-form-item label-width="0">
                <el-col :span="24">
                  <span class="font-red">有来源scm的订单只能一体预约</span>
                </el-col>
              </el-form-item>
            </template>

            <el-form-item
              prop="appointType"
              :rules="[
                {required: true, message: '请选择日期', trigger: 'change'}
              ]"
              label="预约方式">
              <el-radio-group v-model="model.appointType">
                <el-col :span="7">
                  <el-radio label="YT">整体预约</el-radio>
                </el-col>
                <!-- 有来源于 scm 的订单只能配装一体（张伟荣） -->
                <el-col :span="7" v-if="!hasOrderSourceCodeScm" :offset="10">
                  <el-radio label="FL">分离预约</el-radio>
                </el-col>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
      <el-row v-for="(item, index) in model.appointTimes" :key="item.serviceNo">
        <el-col :span="24">
          <el-form-item :label="getTimeLabelText(item.serviceNo)" label-width="110px"
                        :prop="'appointTimes.' + index + '.time'" :rules="[
                    {required: true, message: '请选择日期', trigger: 'change'}
                  ]">
            <el-date-picker :picker-options="pickerOptions" type="date" placeholder="选择年月日" v-model="item.time"
                            value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :prop="'appointTimes.' + index + '.timeCode'" :rules="[
                    {required: true, message: '请选择时间段', trigger: 'change'}
                  ]">
            <el-radio-group v-model="item.timeCode">
              <el-radio v-for="item in timeCodeArr" :key="item.value" :label="item.value">{{ item.text }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="hasMemo">
        <el-col :span="24">
          <el-form-item label="预约备注" label-width="110px" prop="memo">
            <el-input type="textarea" :maxlength="300" placeholder="预约备注" v-model="model.memo"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="hide">取消</el-button>
      <el-button type="primary" @click="postSubmit" :loading="loading">确认提交</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {filterDataBaseDictionary, unixTimestampFilter} from '@/filters'
import {dotData, copy, confirm, alert} from '@/utils'
import {chTimeIntervalGT} from '@/utils/validatorUtil'
import {getTimeInterval} from '@/utils/selectOptions'
import moment from 'moment'

export default {
  filters: {
    filterDataBaseDictionary
  },
  data() {
    return {
      innerVisible: false,
      model: {
        appointTimes: [],
        memo: '',
        appointType: 'YT'
      },
      checkedServices: [],
      timeCodeArr: [],
      type: '',
      isShowMsg: false,
      loading: false,
      httpLoading: false,
      pickerOptions: {
        disabledDate(time) {
          return moment(time).isBefore(Date.now(), 'day')
        }
      },
      serviceNoAll: []
    }
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    rows: {
      type: Array,
      required: true
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    // 暂时上面的服务信息
    showHeader: {
      type: Boolean,
      default: true
    },
    coverTitle: {
      type: String,
      default: ''
    },
    createUrl: {
      type: String,
      default: '/ms-terminal-order/appoint/action'
    },
    hasMemo: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    // 监听 传进来的 visible
    visible(val, oldVal) {
      if (val === oldVal) {
        return
      }
      // 初始化清空值
      this.$nextTick(_ => {
        if (this.hasOrderSourceCodeScm) {
          this.model.appointType = 'YT'
        }
        // 通用预约
        if (this.isEdit) {
          this.getAppointDetails()
        } else {
          this.resetElForm()
          this.setModelAppointTimes()
        }
      })
      this.innerVisible = val
    },
    // 如果内部有新值变化，更新外部visible
    innerVisible(val, oldVal) {
      if (val === oldVal) {
        return
      }
      this.$emit('update:visible', val)
    },
    // 预约类型切换
    'model.appointType'(val, oldVal) {
      this.setModelAppointTimes(val)
    }
  },
  computed: {
    getTitle() {
      return '服务预约'
    },
    // 是否是批量操作
    isBatch() {
      return Array.isArray(this.rows) && this.rows.length > 1
    },
    // 能单独预约不
    canSingleAppoint() {
      return !this.isBatch && this.type !== 'YT' && !this.isEmptyServiceType
    },
    // 所有的服务类型
    serviceTypeList() {
      if (this.isEdit) {
        return this.serviceNoAll || []
      }
      if (Array.isArray(this.rows) && this.rows.length > 0) {
        const item = this.rows[0]
        const serviceNoList = dotData(item, 'serviceNoList')
        if (Array.isArray(serviceNoList)) {
          return serviceNoList.map(v => v.key)
        }
      }
      return []
    },
    idArr() {
      if (Array.isArray(this.rows)) {
        return this.rows.map(v => v.id)
      }
      return []
    },
    orderIdArr() {
      if (Array.isArray(this.rows)) {
        return this.rows.map(v => v.orderId)
      }
      return []
    },
    appointTime() {
      let temp = dotData(this.rows, '[0].appointTime')
      if (temp) {
        return unixTimestampFilter(temp, 'YYYY-MM-DD')
      }
      return ''
    },
    timeCode() {
      return dotData(this.rows, '[0].timeIntervalCode') || ''
    },
    // 备注
    memo() {
      return dotData(this.rows, '[0].memo') || ''
    },
    // 来源于scm的订单
    hasOrderSourceCodeScm() {
      for (let v of this.rows) {
        if (v.orderSourceCode === 'scm') {
          return true
        }
      }
      return false
    }
  },
  created() {
    getTimeInterval().then(arr => {
      this.timeCodeArr = arr
    })
  },
  methods: {
    hide() {
      this.innerVisible = false
    },
    getTimeLabelText(type) {
      if (type === 'YT') {
        return '整体一体'
      } else if (type === 'SCM') {
        return '预约'
      }
      return filterDataBaseDictionary(type) + '预约'
    },
    postSubmit() {
      this.$refs.elForm.validate((valid) => {
        if (!valid) {
          return
        }
        let data = copy(this.model, true)
        let appointTimes = dotData(data, 'appointTimes')
        if (Array.isArray(appointTimes)) {
          const PsRow = dotData(appointTimes.filter(v => v.serviceNo === 'ZpsServiceType01'), '[0]')
          const AzRow = dotData(appointTimes.filter(v => v.serviceNo === 'ZpsServiceType02'), '[0]')
          if (PsRow && AzRow) { // 安装不能早于配送时间
            if (AzRow['time'] <= PsRow['time']) {
              if (AzRow['time'] < PsRow['time']) {
                alert('安装不能早于配送时间')
                return
              }
              if (chTimeIntervalGT(PsRow['timeCode'], AzRow['timeCode'])) {
                alert('安装不能早于配送时间')
                return
              }
            }
          }
        }
        data.ids = this.isEdit ? this.orderIdArr : this.idArr
        this.loading = true
        const url = this.isEdit ? '/ms-terminal-order/appoint/update-appoint' : this.createUrl
        this.$ajax.post(url, data).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            confirm('预约成功').finally(_ => {
              this.hide()
              this.loading = false
              this.$emit('refresh', true)
            })
          } else {
            this.loading = false
          }
        }).catch(_ => {
          this.loading = false
        })
      })
    },
    // 设置模型中的
    setModelAppointTimes(appointType = this.model.appointType) {
      if (this.httpLoading) {
        return
      }
      // 服务类型
      let temp = []
      if (this.hasOrderSourceCodeScm) { // scm
        temp = ['SCM']
      } else {
        if (appointType === 'YT') {
          temp = ['YT']
        } else {
          temp = this.serviceTypeList
        }
      }
      this.model.appointTimes = temp.map(v => {
        return {
          serviceNo: v,
          time: '',
          timeCode: ''
        }
      })
    },
    // 清空改约数据
    resetElForm() {
      const node = this.$refs.elForm
      if (node) {
        this.model.appointTimes = []
        this.$nextTick(_ => {
          node.resetFields()
        })
      }
    },
    // 请求订单数据
    getAppointDetails() {
      const orderId = dotData(this.orderIdArr, '[0]')
      if (orderId) {
        this.httpLoading = true
        this.$ajax.get('/ms-terminal-order/appoint/get-appoint-details', {orderId}).then(response => {
          if (response.success) {
            this.model.appointType = dotData(response, 'data.appointType')
            if (Array.isArray(dotData(response, 'data.appointTimes'))) {
              this.model.appointTimes = dotData(response, 'data.appointTimes')
              this.serviceNoAll = dotData(response, 'data.serviceNoAll')
            }
            this.model.memo = dotData(response, 'data.memo')
          }
        }).finally(_ => {
          this.httpLoading = false
        })
      } else {
        alert('orderId未取得')
      }
    }
  }
}
</script>
